import { _decorator, Component, EventTouch, Node, UITransform, v2, v3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('joystick')
export class joystick extends Component {
    @property(Node) center: Node
    uiTrans: UITransform
    limitR: number = 150
    outDir = v3(0, 0, 0)
    start() {
        this.uiTrans = this.node.getComponent(UITransform)
        this.openTouchEvent()
    }
    getDir() {
        return this.outDir
    }
    openTouchEvent() {
        this.node.on(Node.EventType.TOUCH_START, this.onTouchMoved, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMoved, this);
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }
    onTouchMoved(event: EventTouch) {
        const uiPos = event.getUILocation()
        const cPos = this.uiTrans.convertToNodeSpaceAR(v3(uiPos.x, uiPos.y, 0))
        const length = cPos.length()
        const scale = length > this.limitR ? this.limitR : length
        cPos.normalize().multiplyScalar(scale)
        this.center.setPosition(cPos)
        this.outDir.set(cPos.x, 0, -cPos.y)
    }
    onTouchEnd(event: EventTouch) {
        this.center.setPosition(v3(0, 0))
        this.outDir.set(0, 0, 0)

    }
    update(deltaTime: number) {

    }
}


